package com.newtouch.bxzs.policy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.newtouch.bxzs.common.base.constant.RabbitMQConstant;
import com.newtouch.bxzs.common.base.em.*;
import com.newtouch.bxzs.common.base.model.Policy;
import com.newtouch.bxzs.common.base.model.bo.PushMessageBO;
import com.newtouch.bxzs.common.base.util.CooperationCompanyUtils;
import com.newtouch.bxzs.common.base.util.RabbitMQUtils;
import com.newtouch.bxzs.common.base.util.RedisUtils;
import com.newtouch.bxzs.common.base.util.SendHttpRequestUtils;
import com.newtouch.bxzs.policy.mapper.PolicyNoticeMapper;
import com.newtouch.bxzs.policy.model.vo.*;
import com.newtouch.bxzs.policy.service.PolicyNoticeService;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 保单通知实现类
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021/2/3 14:17</td>
 * <td>linhongxi</td>
 * <td>Create</td>
 * </tr>
 * </table>
 *
 * @author linhongxi
 * @version 1.0.0
 * @since 1.0.0
 */
@Service
public class PolicyNoticeServiceImpl implements PolicyNoticeService {
	@Autowired
	AmqpTemplate rabbitTemplate;

	@Autowired
	private RedisUtils redisUtils;

	@Resource
	private PolicyNoticeMapper policyNoticeMapper;

	@Autowired
	private CooperationCompanyUtils cooperationCompanyUtils;

	@Value("${policy.socialCreditCodeInsurance}")
	private String socialCreditCodeInsurance;

	@Value("${policy.socialCreditCodeBank}")
	private String socialCreditCodeBank;
	/**
	 * 发送投保成功通知 com.newtouch.bxzs.policy.service.PolicyNoticeService#
	 * successfulInsuranceNotice
	 * 
	 * @param insuranceNoticeVO 投保保单信息
	 * @return 通知结果
	 */
	@Override
	public boolean successfulInsuranceNotice(InsuranceNoticeVO insuranceNoticeVO) {
		// 查询是否存在三方关系
		String relationId = policyNoticeMapper.selectRelation(insuranceNoticeVO);
		if (!StringUtils.isEmpty(relationId)) {
			// 将接收到的保单信息新增到保单表中
			Policy insurancePolicy = new Policy();
			insuranceNoticeVO.setUserCustomerCooperationCompanyUserMapId(relationId);
			BeanUtil.copyProperties(insuranceNoticeVO,insurancePolicy);
			insurancePolicy.setCreateTime(new Date());
			insurancePolicy.setCreateUserId(policyNoticeMapper.getUserIdByUserJobNumber(insuranceNoticeVO.getInsuranceUserJobNumber()));
			int result = policyNoticeMapper.insert(insurancePolicy);
			if (result > 0) {
				// 保单信息添加成功后发送投保成功通知
				PushMessageBO message = PushMessageBO.builder().title("保单通知")
						.content(insuranceNoticeVO.getPolicyHolderName() + "已投保成功，保单号为"
								+ insuranceNoticeVO.getPolicyNumber() + "，请知晓!")
						.noticeJumpId(insuranceNoticeVO.getPolicyNumber())
						.policyType(insuranceNoticeVO.getPolicyType())
						.policyNoticeType(PolicyNoticeType.INSURANCE_NOTICE_TYPE.getCode())
						.unifiedSocialCreditCode(insuranceNoticeVO.getDateSource())
						.build();
				rabbitTemplate.convertAndSend(RabbitMQConstant.EXCHANGE_STR, RabbitMQConstant.MESSAGE_NOTICE,
						RabbitMQUtils.createUserJobNumberRabbitMap(insuranceNoticeVO.getInsuranceUserJobNumber(), message,
								BusinessMessageEnum.POLICY_MESSAGE_REMINDER.getResultCode()));
				if (redisUtils.get(SystemParamsEnum.BANKING_OR_INSURANCE.getCode()).equals(DistributionTypeEnum.INSURANCE.getCode())) {
					NoticeUserChangeVO noticeUserChangeVO = changeUser(insuranceNoticeVO);
					BeanUtil.copyProperties(noticeUserChangeVO, insuranceNoticeVO);
					insuranceNoticeVO.setDateSource(socialCreditCodeInsurance);
					SendHttpRequestUtils<InsuranceNoticeVO> sendHttpRequest = new SendHttpRequestUtils<>();
					return (boolean)sendHttpRequest.sendHttpRequest(insuranceNoticeVO,cooperationCompanyUtils.getCompanyUrl(socialCreditCodeBank,
							CompanyParameterTypeEnum.NOTICE_INSURANCE_SUCCESS.getCode()));
				}
				return true;
			}
		}
		return false;
	}

	/**
	 * 发送退保申请通知 com.newtouch.bxzs.policy.service.PolicyNoticeService#
	 * surrenderApplicationNotice
	 *
	 * @param surrenderNoticeVO 保单退保申请信息
	 * @return 通知结果
	 */
	@Override
	public boolean surrenderApplicationNotice(SurrenderNoticeVO surrenderNoticeVO) {
		// 查询是否存在三方关系
		String relationId = policyNoticeMapper.selectRelation(surrenderNoticeVO);
		if (!StringUtils.isEmpty(relationId)) {
			// 将接收到的保单信息修改到保单表中
			int result = policyNoticeMapper.updateSurrenderApplicationPolicy(surrenderNoticeVO, new Date(), relationId);
			if (result > 0) {
				PushMessageBO message = PushMessageBO.builder().title("保单通知")
						.content(surrenderNoticeVO.getPolicyHolderName() + "已申请退保，保单号为"
								+ surrenderNoticeVO.getPolicyNumber() + "，请知晓！")
						.noticeJumpId(surrenderNoticeVO.getPolicyNumber())
						.policyType(surrenderNoticeVO.getPolicyType())
						.policyNoticeType(PolicyNoticeType.SURRENDER_NOTICE_TYPE.getCode())
						.unifiedSocialCreditCode(surrenderNoticeVO.getDateSource())
						.build();
                rabbitTemplate.convertAndSend(RabbitMQConstant.EXCHANGE_STR, RabbitMQConstant.MESSAGE_NOTICE,
                        RabbitMQUtils.createUserJobNumberRabbitMap(surrenderNoticeVO.getInsuranceUserJobNumber(), message,
                                BusinessMessageEnum.POLICY_MESSAGE_REMINDER.getResultCode()));
				if (redisUtils.get(SystemParamsEnum.BANKING_OR_INSURANCE.getCode()).equals(DistributionTypeEnum.INSURANCE.getCode())) {
					NoticeUserChangeVO noticeUserChangeVO = changeUser(surrenderNoticeVO);
					BeanUtil.copyProperties(noticeUserChangeVO, surrenderNoticeVO);
					surrenderNoticeVO.setDateSource(socialCreditCodeInsurance);
					SendHttpRequestUtils<SurrenderNoticeVO> sendHttpRequest = new SendHttpRequestUtils<>();
					return (boolean)sendHttpRequest.sendHttpRequest(surrenderNoticeVO,cooperationCompanyUtils.getCompanyUrl(socialCreditCodeBank,
							CompanyParameterTypeEnum.NOTICE_SURRENDER_APPLICATION.getCode()));
				}
				return true;
			}
		}
		return false;
	}

	/**
	 * 发送退保成功通知 com.newtouch.bxzs.policy.service.PolicyNoticeService#
	 * successfulSurrenderNotice
	 * 
	 * @param successfulSurrenderNoticeVO 保单退保成功相关信息
	 * @return 通知结果
	 */
	@Override
	public boolean successfulSurrenderNotice(SuccessfulSurrenderNoticeVO successfulSurrenderNoticeVO) {
		// 查询是否存在三方关系
		String relationId = policyNoticeMapper.selectRelation(successfulSurrenderNoticeVO);
		if (!StringUtils.isEmpty(relationId)) {
			// 将接收到的保单信息新增到保单表中
			int result = policyNoticeMapper.updateSurrenderPolicy(successfulSurrenderNoticeVO, new Date(), relationId);
			if (result > 0) {
				PushMessageBO message = PushMessageBO.builder().title("保单通知")
						.content(successfulSurrenderNoticeVO.getPolicyHolderName() + "已退保成功，保单号为"
								+ successfulSurrenderNoticeVO.getPolicyNumber() + "，请知晓！")
						.noticeJumpId(successfulSurrenderNoticeVO.getPolicyNumber())
						.policyType(successfulSurrenderNoticeVO.getPolicyType())
						.policyNoticeType(PolicyNoticeType.SURRENDER_NOTICE_TYPE.getCode())
						.unifiedSocialCreditCode(successfulSurrenderNoticeVO.getDateSource())
						.build();
                rabbitTemplate.convertAndSend(RabbitMQConstant.EXCHANGE_STR, RabbitMQConstant.MESSAGE_NOTICE,
                        RabbitMQUtils.createUserJobNumberRabbitMap(successfulSurrenderNoticeVO.getInsuranceUserJobNumber(), message,
                                BusinessMessageEnum.POLICY_MESSAGE_REMINDER.getResultCode()));
				if (redisUtils.get(SystemParamsEnum.BANKING_OR_INSURANCE.getCode()).equals(DistributionTypeEnum.INSURANCE.getCode())) {
					NoticeUserChangeVO noticeUserChangeVO = changeUser(successfulSurrenderNoticeVO);
					BeanUtil.copyProperties(noticeUserChangeVO, successfulSurrenderNoticeVO);
					successfulSurrenderNoticeVO.setDateSource(socialCreditCodeInsurance);
					SendHttpRequestUtils<SuccessfulSurrenderNoticeVO> sendHttpRequest = new SendHttpRequestUtils<>();
					return (boolean)sendHttpRequest.sendHttpRequest(successfulSurrenderNoticeVO,cooperationCompanyUtils.getCompanyUrl(socialCreditCodeBank,
							CompanyParameterTypeEnum.NOTICE_SURRENDER_SUCCESS.getCode()));
				}
				return true;
			}
		}
		return false;
	}

	/**
	 * 保单续期通知 com.newtouch.bxzs.policy.service.PolicyNoticeService#renewalNotice
	 * 
	 * @param renewalNoticeVO 保单续期相关信息
	 * @return 通知结果
	 */
	@Override
	public boolean renewalNotice(RenewalNoticeVO renewalNoticeVO) {
		// 查询是否存在三方关系
		String relationId = policyNoticeMapper.selectRelation(renewalNoticeVO);
		if (!StringUtils.isEmpty(relationId)) {
			// 将接收到的保单信息新增到保单表中
			int result = policyNoticeMapper.updateRenewalPolicy(renewalNoticeVO, new Date(), relationId);
			if (result > 0) {
				PushMessageBO message = PushMessageBO.builder().title("保单通知")
						.content("保单号:"
								+ renewalNoticeVO.getPolicyNumber() + ",即将到达应缴费日期"+ DateUtil.formatDate(renewalNoticeVO.getRenewalPaymentDeadline()))
						.noticeJumpId(renewalNoticeVO.getPolicyNumber())
						.policyType(renewalNoticeVO.getPolicyType())
						.policyNoticeType(PolicyNoticeType.RENEWAL_NOTICE_TYPE.getCode())
						.unifiedSocialCreditCode(renewalNoticeVO.getDateSource())
						.build();
                rabbitTemplate.convertAndSend(RabbitMQConstant.EXCHANGE_STR, RabbitMQConstant.MESSAGE_NOTICE,
                        RabbitMQUtils.createUserJobNumberRabbitMap(renewalNoticeVO.getInsuranceUserJobNumber(), message,
                                BusinessMessageEnum.POLICY_MESSAGE_REMINDER.getResultCode()));
				if (redisUtils.get(SystemParamsEnum.BANKING_OR_INSURANCE.getCode()).equals(DistributionTypeEnum.INSURANCE.getCode())) {
					NoticeUserChangeVO noticeUserChangeVO = changeUser(renewalNoticeVO);
					BeanUtil.copyProperties(noticeUserChangeVO, renewalNoticeVO);
					renewalNoticeVO.setDateSource(socialCreditCodeInsurance);
					SendHttpRequestUtils<RenewalNoticeVO> sendHttpRequest = new SendHttpRequestUtils<>();
					return (boolean)sendHttpRequest.sendHttpRequest(renewalNoticeVO,cooperationCompanyUtils.getCompanyUrl(socialCreditCodeBank,
							CompanyParameterTypeEnum.NOTICE_RENEWAL.getCode()));
				}
				return true;
			}
		}
		return false;
	}

	/**
	 * 保单满期通知 com.newtouch.bxzs.policy.service.PolicyService#expirationNotice
	 * 
	 * @param insuranceNoticeVO 保单满期相关信息
	 * @return 通知结果
	 */
	@Override
	public boolean expirationNotice(InsuranceNoticeVO insuranceNoticeVO) {
		// 查询是否存在三方关系
		String relationId = policyNoticeMapper.selectRelation(insuranceNoticeVO);
		if (!StringUtils.isEmpty(relationId)) {
			// 将接收到的保单信息新增到保单表中
			int result = policyNoticeMapper.updateExpirationPolicy(insuranceNoticeVO, new Date(), relationId);
			if (result > 0) {
				PushMessageBO message = PushMessageBO.builder().title("保单通知")
						.content("保单号:"
								+ insuranceNoticeVO.getPolicyNumber() + ",即将满期结束，满期时间"+ DateUtil.formatDate(insuranceNoticeVO.getPolicyExpirationDate()))
						.noticeJumpId(insuranceNoticeVO.getPolicyNumber())
						.policyType(insuranceNoticeVO.getPolicyType())
						.policyNoticeType(PolicyNoticeType.EXPIRATION_NOTICE_TYPE.getCode())
						.unifiedSocialCreditCode(insuranceNoticeVO.getDateSource())
						.build();
                rabbitTemplate.convertAndSend(RabbitMQConstant.EXCHANGE_STR, RabbitMQConstant.MESSAGE_NOTICE,
                        RabbitMQUtils.createUserJobNumberRabbitMap(insuranceNoticeVO.getInsuranceUserJobNumber(), message,
                                BusinessMessageEnum.POLICY_MESSAGE_REMINDER.getResultCode()));
				if (redisUtils.get(SystemParamsEnum.BANKING_OR_INSURANCE.getCode()).equals(DistributionTypeEnum.INSURANCE.getCode())) {
					NoticeUserChangeVO noticeUserChangeVO = changeUser(insuranceNoticeVO);
					BeanUtil.copyProperties(noticeUserChangeVO, insuranceNoticeVO);
					insuranceNoticeVO.setDateSource(socialCreditCodeInsurance);
					SendHttpRequestUtils<InsuranceNoticeVO> sendHttpRequest = new SendHttpRequestUtils<>();
					return (boolean)sendHttpRequest.sendHttpRequest(insuranceNoticeVO,cooperationCompanyUtils.getCompanyUrl(socialCreditCodeBank,
							CompanyParameterTypeEnum.NOTICE_EXPIRATION.getCode()));
				}
				return true;
			}
		}
		return false;
	}

	/**
	 * 交换两端业务员信息
	 *
	 * @param insuranceNoticeVO 保单信息
	 * @return 交换后的业务员信息
	 */
	private NoticeUserChangeVO changeUser(InsuranceNoticeVO insuranceNoticeVO) {
		NoticeUserChangeVO noticeUserChangeVO = new NoticeUserChangeVO();
		noticeUserChangeVO.setBankUserName(insuranceNoticeVO.getInsuranceUserName());
		noticeUserChangeVO.setBankUserJobNumber(insuranceNoticeVO.getInsuranceUserJobNumber());
		noticeUserChangeVO.setBankUserCertificateType(insuranceNoticeVO.getInsuranceUserCertificateType());
		noticeUserChangeVO.setBankUserCertificateNumber(insuranceNoticeVO.getInsuranceUserCertificateNumber());
		noticeUserChangeVO.setInsuranceUserName(insuranceNoticeVO.getBankUserName());
		noticeUserChangeVO.setInsuranceUserJobNumber(insuranceNoticeVO.getBankUserJobNumber());
		noticeUserChangeVO.setInsuranceUserCertificateType(insuranceNoticeVO.getBankUserCertificateType());
		noticeUserChangeVO.setInsuranceUserCertificateNumber(insuranceNoticeVO.getBankUserCertificateNumber());
		return noticeUserChangeVO;
	}
}
